package com.tt5.services.vertx.handlers

import com.tt5.services.vertx.keyTraceId
import com.tt5.services.vertx.requestToString
import com.tt5.services.vertx.responseToString
import com.tt5.services.vertx.traceId
import io.vertx.core.impl.logging.LoggerFactory
import io.vertx.ext.web.RoutingContext
import java.util.UUID

object LogHandler {
  private val logger = LoggerFactory.getLogger(LogHandler.javaClass)

  suspend fun log(ctx: RoutingContext) {
    var traceId = ctx.request().getHeader(keyTraceId)
    if (traceId.isNullOrEmpty()) {
      traceId = UUID.randomUUID().toString()
      ctx.request().headers().add(keyTraceId, traceId)
    }
    ctx.traceId = traceId
    ctx.response().headers().add(keyTraceId, traceId)
    logger.debug("Request: ${ctx.requestToString()}")
    ctx.addEndHandler { it ->
      logger.debug("Response: ${ctx.responseToString()}")
    }
    ctx.next()
  }
}
